package com.yzjs.common.util.check;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XssFilterUtil {

    private static List<Pattern> patterns = null;

    private static Map<Character, String> ILLEGAL_CHARACTER = new HashMap<>();

    static {
        ILLEGAL_CHARACTER.put('<', "&lt;");
        ILLEGAL_CHARACTER.put('>', "&gt;");
        ILLEGAL_CHARACTER.put('"', "&quot;");
        ILLEGAL_CHARACTER.put('\'', "&#39;");
        ILLEGAL_CHARACTER.put('%', "&#37;");
        ILLEGAL_CHARACTER.put(';', "&#59;");
        ILLEGAL_CHARACTER.put('(', "&#40;");
        ILLEGAL_CHARACTER.put(')', "&#41;");
        ILLEGAL_CHARACTER.put('&', "&amp;");
        ILLEGAL_CHARACTER.put('+', "&#43;");
    }

    private static List<Object[]> getXssPatternList() {
        List<Object[]> ret = new ArrayList<>();
        ret.add(new Object[]{"<(no)?script[^>]*>.*?</(no)?script>", Pattern.CASE_INSENSITIVE});
        ret.add(new Object[]{"eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"(javascript:|vbscript:|view-source:)*", Pattern.CASE_INSENSITIVE});
        ret.add(new Object[]{"<(\"[^\"]*\"|\'[^\']*\'|[^\'\">])*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*|window|location", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        return ret;
    }

    private static List<Pattern> getPatterns() {
        if (patterns == null) {
            List<Pattern> list = new ArrayList<>();
            String regex;
            Integer flag;
            int arrLength;
            for (Object[] arr : getXssPatternList()) {
                arrLength = arr.length;
                for (int i = 0; i < arrLength; i++) {
                    regex = (String) arr[0];
                    flag = (Integer) arr[1];
                    list.add(Pattern.compile(regex, flag));
                }
            }
            patterns = list;
        }
        return patterns;
    }

    public static boolean validate(String... value) {
        boolean flag = true;
        if (value != null && value.length > 0) {
            for (String val : value) {
                if (val != null && !val.equals(stripXss(val))) {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    public static String stripXss(String value) {
        if (null == value) {
            return null;
        }
        if (StringUtils.isNotBlank(value)) {
            value = Jsoup.parse(value).text();
            Matcher matcher;
            for (Pattern pattern : getPatterns()) {
                matcher = pattern.matcher(value);
                // 匹配
                if (matcher.find()) {
                    // 删除相关字符串
                    value = matcher.replaceAll("");
                }
            }
//			filter(value);
        }
        // 预防SQL盲注
//        String[] pattern = {"%", "+", "'", "\"", "||", "select", "insert", "delete", "from", "count\\(", "drop table", "update", "truncate", "asc\\(", "mid\\(", "char\\(", "xp_cmdshell", "exec", "master", "netlocalgroup administrators", "net user", "or", "and"};
//        for (String patern : pattern) {
//            value = value.replace(patern, "");
//        }
        String regex = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\\b((?i)frame|<(?i)frame|(?i)iframe|<(?i)iframe|(?i)img|<(?i)img|(?i)javascript|<(?i)javascript|(?i)script|<(?i)script|(?i)alert|(?i)select|(?i)update|(?i)and|(?i)or|(?i)delete|(?i)insert|(?i)trancate|(?i)char|(?i)substr|(?i)ascii|(?i)declare|(?i)exec|(?i)count|(?i)master|(?i)into|(?i)drop|(?i)execute)\\b)";
        value = value.replaceAll(regex, "");
        return value;
    }

    public static String filter(String value) {
        if (StringUtils.isBlank(value))
            return value;
        final StringBuilder result = new StringBuilder();
        final StringCharacterIterator iterator = new StringCharacterIterator(value);
        char character = iterator.current();
        while (character != CharacterIterator.DONE) {
            for (Entry<Character, String> entry : ILLEGAL_CHARACTER.entrySet()) {
                if (character == entry.getKey()) {
                    result.append(entry.getValue());
                    break;
                } else if (!ILLEGAL_CHARACTER.keySet().contains(character)) {
                    // the char is not a special one
                    // add it to the result as is
                    result.append(character);
                    break;
                }
            }
            character = iterator.next();
        }
        return result.toString();
    }
}
